import {
  IAdditionalData,
  IContactDataModel
} from '../../common/commlib.interfaces';
import {
  GroupChannel,
  SendBirdInstance,
  GroupChannelListQuery
} from 'sendbird';
// import * as request from 'request';

export class SendBirdAdditionalData implements IAdditionalData {
  private apiUrl: string;
  private apiToken: string;
  private unassignedChannelsQuery: GroupChannelListQuery;
  constructor(private sendbirdInstance: SendBirdInstance, parameters: any) {
    this.apiToken = parameters.apiToken || '';
    this.apiUrl = parameters.apiRequestUrl || '';
  }
  public getUnassignContacts(): Promise<IContactDataModel[]> {
    return new Promise((resolve, reject) => {
      if (!this.sendbirdInstance) {
        reject('There is no connection to sendbird.');
        return;
      }
      if (!this.apiUrl || !this.apiToken) {
        reject('The apiRequestUrl or apiToken is not provided.');
        return;
      }

      this.unassignedChannelsQuery = this.sendbirdInstance.GroupChannel.createMyGroupChannelListQuery();
      this.unassignedChannelsQuery.limit = 20;
      this.unassignedChannelsQuery.includeEmpty = true;
      this.unassignedChannelsQuery.customTypeFilter = 'unassigned';

      if (this.unassignedChannelsQuery.hasNext) {
        this.unassignedChannelsQuery.next((groupChannels, error) => {
          if (error) {
            reject(`Retrieve unassigned contacts failed with error: ${error}`);
            return;
          }

          const contacts = groupChannels.map((channel: GroupChannel) => {
            const contact: IContactDataModel = {
              id: channel.url,
              name: channel.name,
              state: 'unassigned',
              createdAt: channel.createdAt,
              createdBy: channel.inviter.userId
            };
            return contact;
          });

          resolve(contacts);
        });
      }
    });
  }

  public deleteMessage(contactId: string, messageId: string): any {
    return new Promise((resolve, reject) => {
      if (!this.apiUrl || !this.apiToken) {
        reject('The apiRequestUrl or apiToken is not provided.');
        return;
      }
      if (!contactId || !messageId) {
        reject('The contactId and messageId are mandatory.');
        return;
      }
      resolve(true);
      /* const httpOptions = {
        url: `${this.apiUrl}/group_channels/${contactId}/messages/${messageId}`,
        headers: {
          'Content-Type': 'application/json, charset=utf8',
          'Api-Token': this.apiToken
        }
      }; */
      /* request.delete(httpOptions, (error, response) => {
        if (error) {
          reject(`[${response.statusCode}] ${error}`);
        } else {
          resolve(true);
        }
      }); */
    });
  }
}
